<template>
  <div>

    <el-row>
      <el-col :span="20">

        <div body-style="padding:20px">
          <div style="margin-bottom: 15px" class="toolbox">

            <button class="plainButton" @click="importSql" >
              导入建表SQL
            </button>

            <button class="plainButton" @click="openTables" >
              导入表
            </button>

            <!-- <button class="plainButton w100" @click="doCreateEntity" >
              生成Entity
            </button>
            <button class="plainButton w100" @click="doCreateVo" >
              生成Vo
            </button>
            <button class="plainButton w110" @click="doCreateMapperJ" >
              生成MapperJ
            </button>
            <button class="plainButton w110" @click="doCreateMapperX" >
              生成MapperX
            </button> -->


          </div>

          <div class="manage-header">
            <CommonForm
              :formItemList="tableInfoForm.formItemList"
              :formData="tableInfoForm.formData"
              :inline="tableInfoForm.inline"
            >
              <template v-slot>
                <el-select v-model="commonModel" placeholder="请选择通用模板" clearable  :multiple="false">
                  <el-option v-for="(item, index) in commonModelOptions" :key="index" :label="item.name"
                             :value="item.id"
                  ></el-option>
                </el-select>
                <el-button @click="createZdy">自定义生成</el-button>

              </template>
            </CommonForm>
            <div class="fr">
              <el-button style="background: #409EFF;" @click="addRow">新增一行</el-button>
              <el-button style="background: #409EFF;" @click="getSQL">转储SQL</el-button>
            </div>

          </div>


          <!--    数据表格-->
          <div style="height: 800px">
            <CommonTable
              :tableData="table.tableData"
              :tableLabel="table.tableLabel"
              :pageConfig="table.pageConfig"
              :defaultButtons = "true"
              :noEdit="true"
              :operationWidth="60"
            >

            </CommonTable>

          </div>
        </div>
      </el-col>
      <el-col :span="4">
        <div style="margin-left:4px;margin-top:100px;padding-left:6px">

          <el-card class="box-card">
            <div slot="header" class="clearfix">
              <el-button style="float: right; padding: 3px 0" type="text" @click="mock">模拟常用数据</el-button>
            </div>
            <div v-for="item in mockData" :key="item.name" class="text item">
              <div style="font-weight: 600;margin-bottom: 4px">{{item.name}}</div>{{item.value}}
            </div>
          </el-card>
        </div>

      </el-col>
    </el-row>

    <!-- 导入建表SQL -->
    <el-dialog
      :title="'导入建表SQL'"
      :visible.sync="dialogImpSQlForm.isShow"
    >
      <el-input
        type="textarea"
        :rows="16"
        placeholder="请输入SQL"
        style="font-size: 16px"
        v-model="dialogImpSQlForm.formData.sql">
      </el-input>

      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogImpSQlForm.isShow = false">取消</el-button>
        <el-button type="primary" @click="doImportSql">确定</el-button>
      </div>
    </el-dialog>


    <el-drawer title="导入表" :visible.sync="sliderVisible" width="40%" >
      <div style="padding: 2px 10px">
        <el-select
          :placeholder="'请选择所属项目'"
          v-model="query.projectId"
          @change="initTables"
        >
          <el-option
            v-for="option in projectOptions"
            :key="option.id"
            :label="option.name"
            :value="option.id"
          />
        </el-select> &nbsp;
        <el-input
          :placeholder="'请输入关键字'"
          v-model.trim="query.tableName"
          :prefix-icon="'el-icon-search'"
          style="width: 200px"
          @input="initTables"
        />
      </div>
      <el-collapse :key="collapseKey">
        <el-collapse-item style="padding: 20px" :title="item.remark + ' - ' + item.tableName" v-for="(item,index) in tables" :key="index">
          <el-card>
            <p><b>字段: </b>{{ item.fields }}</p>
            <div>
              <el-button type="primary" class="fr mb10 ml10" @click="importTable(item)">导入</el-button>
              <el-button type="danger" class="fr mb10 " @click="delTable(item)">删除</el-button>
            </div>
          </el-card>
        </el-collapse-item>
      </el-collapse>
    </el-drawer>


    <!-- 模板预览 -->
    <el-dialog
      :title="'模板预览'"
      :visible.sync="isShowModule"
      width="800px"
    >
      <div style="position: relative">
        <a href="#" class="copy-button" style="position: absolute;right: 10px;top:8px;color: #fff;z-index: 999">复制</a>
        <div v-html="targetTxt"></div>
      </div>


      <div slot="footer" class="dialog-footer">
        <el-button @click="isShowModule = false">取消</el-button>
      </div>
    </el-dialog>


  </div>
</template>
<script>

import CommonForm from '../../components/CommonForm'
import CommonTable from '../../components/CommonTable'
import {
  addFromSql,
  findColumns,
  findTables,
  deleteOne,
  createEntity,
  createVo,
  findById,
  createMapperJ,
  createMapperX, addBlankRow
} from '../../api/table'
import {edit} from '../../api/column'
import {createCommonModule, getCommonList} from '../../api/module'
import CommonHeader from "@/components/CommonHeader";
import Prism from 'prismjs'
import Clipboard from 'clipboard';
import request from '../../utils/request'
import vPinyin from "@/utils/pinyin";
import {findDataForSelect} from "@/api/project";
//引入mock模块
import Mock from 'mockjs';

export default {
  name: 'Home',
  components: {
    CommonForm,
    CommonTable
  },

  data() {
    return {
      mockData: [],
      projectOptions:[],
      collapseKey:1,
      query : {
        tableName:'' // 查询参数
      },
      targetTxt:'',
      ids: [] , //选中的行
      commonModel: '',
      commonModelOptions:[],
      moduleText:'',
      isShowModule: false,
      currenttable: {},
      tableInfoForm: {
        formItemList: [
          {
            name: 'tableName',
            label: '表名',
            type: 'input'
          },
          {
            name: 'remark',
            label: '描述',
            type: 'input'
          },
          {
            name: 'projectId',
            label: '所属项目',
            type: 'select',
            icon: 'el-icon-search',
            optionList: []
          }
        ],
        formData: {
          tableName:'',
          remark:'',
          projectId:''
        },
        inline: true
      },
      dialogImpSQlForm: {
        isShow: false,
        formData: {
          sql: ''
        },
        inline: true
      },
      table: {
        tableData: [],
        tableLabel: [
          {
            name: 'columnComment',
            label: '名称',
            type: 'edit',
            editType: 'name', //编辑中文名称额外更新字段
            width:  70
          },

          {
            name: 'columnName',
            label: '字段',
            type: 'edit',
            width: 80
          },
          {
            name: 'columnType',
            label: '类型',
            type: 'edit',
            width: 60
          },
          // {
          //   name: 'dict',
          //   label: '字典',
          //   type: 'edit',
          //   width: 60
          // },
          // {
          //   name: 'sensitiveRule',
          //   label: '脱敏规则',
          //   type: 'edit',
          //   width: 60
          // },
          {
            name: 'mrz',
            label: '默认值',
            type: 'edit',
            width: 60
          },

        ],
        pageConfig: {
          total: 10, // 记录总数
          current: 1, // 起始页
          size: 10 // 每页展示的记录数
        }
      },
      sliderVisible:false,
      tables:[],
      tid:null, //当前表的ID
    }
  }
  ,
  computed: {

  },

  watch: {

  },
  methods: {

    /**
     * 模拟数据
     */
    mock() {
      this.mockData = [];
      const data = Mock.mock({
        name: '@cname()',
        idCard: '@id()',
        address: '@city(true)' // 如果@city(),只会生成市，如果@city(true)会生成省和市
      })
      this.mockData.push({name:'身份证号',value: data.idCard});
      this.mockData.push({name:'姓名',value: data.name});
      this.mockData.push({name:'手机号',value:this.generatePhoneNumber()});
      this.mockData.push({name:'地址',value: getRandomAddr()});
    },

    search(list){
      this.table.tableData = list
    },

    reset(){

    },

    /**
     * 导入建表SQL
     */
    importSql(){
      this.dialogImpSQlForm.isShow = true;
      this.dialogImpSQlForm.formData.sql = ''
      // alert(this.tableInfoForm.formData.projectId)
      if(!this.tableInfoForm.formData.projectId){
        this.$message.error('未识别到项目，请选择一个项目！')
      }
    },

    /**
     * 确定导入建表SQL
     */
    doImportSql(){
      if(!this.dialogImpSQlForm.formData.sql){
        this.$message.error('SQL不允许为空！')
        return
      }
      addFromSql({sql:this.dialogImpSQlForm.formData.sql,pid:this.tableInfoForm.formData.projectId}).then(response => {
        if (response.code === 200) {
          this.$message.success("SQL导入成功！")
          this.dialogImpSQlForm.isShow = false;
          let tid = response.data;
          //再根据刚刚生成的tableId获取字段数据
          // findColumns(tid).then(columnResponse => {
          //   if(columnResponse.code === 200) {
          //     this.search(columnResponse.data)
          //   }
          // })
          //设置当前表
          localStorage.setItem("currenttable",tid)

          findById(tid).then(response => {
            let data = response.data;
            this.importTable(data)
          });

        } else {
          this.$message.error(response.message())
        }
      })
    },

    /**
     * 打开表选择页面
     */
    openTables(){
      this.sliderVisible = true
    },

    /**
     * 导入表
     * @param table
     */
    importTable(table){
      this.sliderVisible = false;
      let tid = table.id;
      this.tid = tid;
      this.tableInfoForm.formData.tableName = table.tableName;
      this.tableInfoForm.formData.remark = table.remark;
      this.tableInfoForm.formData.projectId = table.pid;
      this.loadCommon()
      //再根据刚刚生成的tableId获取字段数据
      findColumns(tid).then(columnResponse => {
        if(columnResponse.code === 200) {
          this.search(columnResponse.data)
        }
      })
      this.currenttable = table;
      localStorage.setItem("currenttable",JSON.stringify(table))
    },

    /**
     * 删除表
     * @param table
     */
    delTable(table){
      if(!confirm("您确定要删除吗？"))
        return
      deleteOne(table.id).then(
        response => {
          if (response.code === 200) {
            this.$message.success("删除成功！")
            this.initTables();
          } else {
            this.$message.error("删除失败！")
          }
        }
      )
    },

    /**
     * 查询表
     */
    initTables(){
      this.collapseKey += 1;
      //加载所有表
      findTables(this.query).then(response => {
        this.tables = response.data.list
        setTimeout(() => {
          highlightText(this.query.tableName);
        },200)
      })


    },

    /**
     * 自定义模板
     */
    createZdy(){
      //模板编号
      let moduleId = this.commonModel;
      let ids = this.ids;
      //字段id集合
      let fields=[];
      fields.push.apply(fields,ids);
      if(fields.length == 0) {
        this.$message.error('请至少选择一个字段！')
        return;
      }

      createCommonModule({moduleId,fields:fields.join(',')}).then(response => {
        this.isShowModule = true;
        this.moduleText = response.data.data;
        this.targetTxt = "<pre><code class=\"language-javascript line-numbers\">"+this.moduleText+"</code></pre>";
        setTimeout(() => {
          Prism.highlightAll()
        }, 200)
      });

    },

    /**
     * 生成Entity
     */
    doCreateEntity(){
      let projectId = this.tableInfoForm.formData.projectId;
      if(!projectId){
        this.$message.error('所属项目不能为空！')
        return
      }
      createEntity(this.tid,projectId).then(response => {
        this.isShowModule = true;
        this.moduleText = response.data.data;
        this.targetTxt = "<pre><code class=\"language-javascript line-numbers\">"+this.moduleText+"</code></pre>";
        setTimeout(() => {
          Prism.highlightAll()
        }, 200)
      })
    },
    /**
     * 生成Vo
     */
    doCreateVo(){
      let projectId = this.tableInfoForm.formData.projectId;
      if(!projectId){
        this.$message.error('所属项目不能为空！')
        return
      }
      createVo(this.tid,projectId).then(response => {
        this.isShowModule = true;
        this.moduleText = response.data.data;
        this.targetTxt = "<pre><code class=\"language-javascript line-numbers\">"+this.moduleText+"</code></pre>";
        setTimeout(() => {
          Prism.highlightAll()
        }, 200)
      })
    },

    /**
     * 生成mapper.java
     */
    doCreateMapperJ(){
      let projectId = this.tableInfoForm.formData.projectId;
      if(!projectId){
        this.$message.error('所属项目不能为空！')
        return
      }
      createMapperJ(this.tid,projectId).then(response => {
        this.isShowModule = true;
        this.moduleText = response.data.data;
        this.targetTxt = "<pre><code class=\"language-javascript line-numbers\">"+this.moduleText+"</code></pre>";
        setTimeout(() => {
          Prism.highlightAll()
        }, 200)
      })
    },
    /**
     * 生成mapper.xml
     */
    doCreateMapperX(){
      let projectId = this.tableInfoForm.formData.projectId;
      if(!projectId){
        this.$message.error('所属项目不能为空！')
        return
      }
      createMapperX(this.tid,projectId).then(response => {
        this.isShowModule = true;
        this.moduleText = response.data.data;
        this.targetTxt = "<pre><code class=\"language-xml line-numbers\">"+this.moduleText+"</code></pre>";
        setTimeout(() => {
          Prism.highlightAll()
        }, 200)
      })
    },

    /**
     * 直接表格上编辑列
     * 常用字段自动映射（暂时写死，不做成动态的了）
     */
    statusChange(row,etype) {
      let comment = row.columnComment;
      if(!comment)
        return;

      if(etype === 'name') {
        //字段英文
        if(!row.columnName && comment != '主键'){
          row.columnName = vPinyin.chineseToPinYinSimple(comment)
        }

        if(comment == '主键'){
          row.columnName = 'id'

        }
        // debugger
        //字段类型
        if(!row.columnType){
          if(comment.indexOf('时间') !== -1 || comment.indexOf('日期') !== -1 ) {
            row.columnType = 'datetime'
          }else
          if(comment.indexOf('版本') !== -1
              || comment.indexOf('数量') !== -1 || comment.indexOf('个数') !== -1) {
            row.columnType = 'int'
          }else if(comment.indexOf('金额') !== -1) {
            row.columnType = 'decimal(10,2)'
          }else if(comment.indexOf('主键') !== -1) {
            row.columnType = 'varchar(80)'
            return;
          }else if(comment.endsWith('附件')) {
            row.columnType = 'varchar(2000)'
          }else{
            row.columnType = 'varchar(50)'
          }
        }

        //默认值
        if(!row.mrz){
          if(comment.indexOf('附件') !== -1) {
            row.mrz = ' DEFAULT \'[]\' '
          }else {
            row.mrz = ' DEFAULT NULL '
          }
        }

      }

      edit(row).then(res => {
        this.importTable(this.currenttable)
      })
    },

    /**
     * 删除列
     */
    handleDelete(id) {
      request({
        url: '/column/' + id,
        method: 'delete',
      }).then(res => {
        this.$message.success('删除成功')
        this.loadColumns();
      })
    },

    /**
     * 加一行
     */
    addRow(){
      let tid = this.tid;
      if(!tid) {
        this.$message.error('当前未选择表！')
        return
      }
      addBlankRow(tid).then(res => {
        this.$message.success('添加成功')
        // 重新导入表
        findById(tid).then(response => {
          let data = response.data;
          this.importTable(data)
        });
      })
    },

    /**
     * 转储SQL
     */
    getSQL(){
      let tid = this.tid;
      let tableName = this.tableInfoForm.formData.tableName;
      let remark = this.tableInfoForm.formData.remark;
      if(!tid || !tableName) {
        this.$message.error('当前未选择表！')
        return
      }
      findColumns(tid).then(response => {
        let data = response.data;
        let createTableSQL = generateCreateTableSQL(data,tableName,remark);
        this.isShowModule = true;
        this.moduleText = createTableSQL;
        this.targetTxt = "<pre><code class=\"language-javascript line-numbers\">"+this.moduleText+"</code></pre>";
        setTimeout(() => {
          Prism.highlightAll()
        }, 200)
      });
    },

    /**
     * 加载表字段
     */
    loadColumns(){
      //加载表字段
      const tid = this.$route.query.tid;
      if(tid) {
        //获取当前的表
        findById(tid).then(response => {
          let data = response.data;
          this.importTable(data)
        });
      }else{
        //加载最近的表
        let tableStr = localStorage.getItem("currenttable")
        if(tableStr) {
          this.currenttable = JSON.parse(tableStr)
          this.importTable(this.currenttable)
        }
      }
    },

    loadProjects() {
      findDataForSelect().then(response => {
        response.data.forEach(obj => {
          // 只是作为演示，如果有字段不同，不劳烦后端处理了
          if (obj.hasOwnProperty('tableName')) {
            obj.name = obj.tableName;
            delete obj.tableName; // 删除原来的tableName属性（可选）
          }
        });
        this.projectOptions = response.data;
        /*this.searchForm.formItemList[0].optionList = this.projectOptions;
        this.dialogForm.formItemList[0].optionList = this.projectOptions;*/
        console.log(this.projectOptions)
        this.tableInfoForm.formItemList[2].optionList = this.projectOptions;

      });
    },

    //所属项目改变
    projectChange(){
      this.initTables();
    },

    loadCommon(){
      //查询通用模板列表
      if(this.tableInfoForm.formData.projectId) {
        getCommonList({projectId:this.tableInfoForm.formData.projectId}).then(res => {
          this.commonModelOptions = res.data
        })
      }
    }

  },
  created() {
    this.initTables();
    this.loadCommon();
    this.loadColumns();
    this.loadProjects();
    this.mock();

    //加载字典
    findDataForSelect().then(response => {
      response.data.forEach(obj => {
        // 只是作为演示，如果有字段不同，不劳烦后端处理了
        if (obj.hasOwnProperty('tableName')) {
          obj.name = obj.tableName;
          delete obj.tableName; // 删除原来的tableName属性（可选）
        }
      });
      this.projectOptions = response.data;

    });
  }
  ,
  mounted() {
    const clipboard = new Clipboard('.copy-button', {
      text: () => this.moduleText
    });
    clipboard.on('success', e => {
      this.$message.success('复制成功')
      console.log(1)
    });
    clipboard.on('error', e => {
      console.log('复制失败');
    });

    this.$bus.$on("sizeChange", size => {
      this.table.pageConfig.size = size
      this.loading()
    })
    this.$bus.$on("currentChange", current => {
      this.table.pageConfig.current = current
      this.loading()
    })
    this.$bus.$on("del", row => {
      this.handleDelete(row.id)
    })
    this.$bus.$on("edit", row => {
      this.handleEdit(row)
    })
    this.$bus.$on("selectionChange", val => {
      this.ids = val.map(item => item.id) // [{},{},{}] => [1,2,3]
    })
    //所属项目值变化
    this.$bus.$on("projectIdChange", current => {
      console.log(current)
      this.loadCommon()
    })
  }
  ,
  beforeDestroy() {
    // 销毁事件
    this.$bus.$off("sizeChange")
    this.$bus.$off("currentChange")
    this.$bus.$off("del")
    this.$bus.$off("edit")
    this.$bus.$off("selectionChange")
    this.$bus.$off("projectIdChange")
  }
}


/**
 * 关键词高亮
 * @param textToHighlight
 */
function highlightText(textToHighlight) {
  let nodes = document.getElementsByClassName('el-collapse-item__header');
  for (let i = 0; i < nodes.length; i++) {
    nodes[i].innerHTML = nodes[i].innerHTML.replace(textToHighlight,`<font color=red> ${textToHighlight} </font>`)
  }
}

/**
 * 转换为建表语句
 * @param columns
 * @returns {string}
 */
function generateCreateTableSQL(columns,tableName,tableRemark) {

  // 构造完整的建表SQL语句
  let sql = `CREATE TABLE ${tableName} (\n\t\`id\` varchar(80) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NOT NULL COMMENT '主键',\n`;

  // 映射每个列到SQL定义
  let columnDefinitions = columns.map(col => {

    if(col.columnComment === '主键')
      return '';

    let sqlDef = `\t${col.columnName} ${col.columnType}`;

    if(col.columnComment && col.columnComment.indexOf('附件') !== -1){
      sqlDef += ` CHARACTER SET utf8mb4   `;
    }else{
      sqlDef += ` COLLATE utf8mb4_general_ci `;
    }

    if (col.notNull === 1) {
      sqlDef += ' NOT NULL';
    }else {
      if(col.mrz){
        sqlDef += ` ${col.mrz}`
      }else {
        sqlDef += ` DEFAULT NULL `
      }
    }



    if (col.columnComment) {
      sqlDef += ` COMMENT '${col.columnComment}' `;
    }

    return sqlDef;
  });



  sql += columnDefinitions.filter(e => e != '').join(',\n');

  // 添加主键约束（如果是id字段）
  sql += `,\n\tPRIMARY KEY (\`id\`) USING BTREE`;

  sql += '\n) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_general_ci ROW_FORMAT=DYNAMIC COMMENT=\'' + tableRemark + '\';';

  return sql;
}

/**
 * 获取随机地址
 */

  var jsonData = {"code":"320000","region":"江苏省","regionEntitys":[{"code":"320100","region":"南京市","regionEntitys":[{"code":"320101","region":"市辖区"},{"code":"320102","region":"玄武区"},{"code":"320104","region":"秦淮区"},{"code":"320105","region":"建邺区"},{"code":"320106","region":"鼓楼区"},{"code":"320111","region":"浦口区"},{"code":"320113","region":"栖霞区"},{"code":"320114","region":"雨花台区"},{"code":"320115","region":"江宁区"},{"code":"320116","region":"六合区"},{"code":"320117","region":"溧水区"},{"code":"320118","region":"高淳区"}]},{"code":"320200","region":"无锡市","regionEntitys":[{"code":"320201","region":"市辖区"},{"code":"320205","region":"锡山区"},{"code":"320206","region":"惠山区"},{"code":"320211","region":"滨湖区"},{"code":"320213","region":"梁溪区"},{"code":"320214","region":"新吴区"},{"code":"320281","region":"江阴市"},{"code":"320282","region":"宜兴市"}]},{"code":"320300","region":"徐州市","regionEntitys":[{"code":"320301","region":"市辖区"},{"code":"320302","region":"鼓楼区"},{"code":"320303","region":"云龙区"},{"code":"320305","region":"贾汪区"},{"code":"320311","region":"泉山区"},{"code":"320312","region":"铜山区"},{"code":"320321","region":"丰县"},{"code":"320322","region":"沛县"},{"code":"320324","region":"睢宁县"},{"code":"320381","region":"新沂市"},{"code":"320382","region":"邳州市"}]},{"code":"320400","region":"常州市","regionEntitys":[{"code":"320401","region":"市辖区"},{"code":"320402","region":"天宁区"},{"code":"320404","region":"钟楼区"},{"code":"320411","region":"新北区"},{"code":"320412","region":"武进区"},{"code":"320413","region":"金坛区"},{"code":"320481","region":"溧阳市"}]},{"code":"320500","region":"苏州市","regionEntitys":[{"code":"320501","region":"市辖区"},{"code":"320505","region":"虎丘区"},{"code":"320506","region":"吴中区"},{"code":"320507","region":"相城区"},{"code":"320508","region":"姑苏区"},{"code":"320509","region":"吴江区"},{"code":"320581","region":"常熟市"},{"code":"320582","region":"张家港市"},{"code":"320583","region":"昆山市"},{"code":"320585","region":"太仓市"}]},{"code":"320600","region":"南通市","regionEntitys":[{"code":"320601","region":"市辖区"},{"code":"320602","region":"崇川区"},{"code":"320611","region":"港闸区"},{"code":"320612","region":"通州区"},{"code":"320621","region":"海安县"},{"code":"320623","region":"如东县"},{"code":"320681","region":"启东市"},{"code":"320682","region":"如皋市"},{"code":"320684","region":"海门市"}]},{"code":"320700","region":"连云港市","regionEntitys":[{"code":"320701","region":"市辖区"},{"code":"320703","region":"连云区"},{"code":"320706","region":"海州区"},{"code":"320707","region":"赣榆区"},{"code":"320722","region":"东海县"},{"code":"320723","region":"灌云县"},{"code":"320724","region":"灌南县"}]},{"code":"320800","region":"淮安市","regionEntitys":[{"code":"320801","region":"市辖区"},{"code":"320803","region":"淮安区"},{"code":"320804","region":"淮阴区"},{"code":"320812","region":"清江浦区"},{"code":"320813","region":"洪泽区"},{"code":"320826","region":"涟水县"},{"code":"320830","region":"盱眙县"},{"code":"320831","region":"金湖县"}]},{"code":"320900","region":"盐城市","regionEntitys":[{"code":"320901","region":"市辖区"},{"code":"320902","region":"亭湖区"},{"code":"320903","region":"盐都区"},{"code":"320904","region":"大丰区"},{"code":"320921","region":"响水县"},{"code":"320922","region":"滨海县"},{"code":"320923","region":"阜宁县"},{"code":"320924","region":"射阳县"},{"code":"320925","region":"建湖县"},{"code":"320981","region":"东台市"}]},{"code":"321000","region":"扬州市","regionEntitys":[{"code":"321001","region":"市辖区"},{"code":"321002","region":"广陵区"},{"code":"321003","region":"邗江区"},{"code":"321012","region":"江都区"},{"code":"321023","region":"宝应县"},{"code":"321081","region":"仪征市"},{"code":"321084","region":"高邮市"}]},{"code":"321100","region":"镇江市","regionEntitys":[{"code":"321101","region":"市辖区"},{"code":"321102","region":"京口区"},{"code":"321111","region":"润州区"},{"code":"321112","region":"丹徒区"},{"code":"321181","region":"丹阳市"},{"code":"321182","region":"扬中市"},{"code":"321183","region":"句容市"}]},{"code":"321200","region":"泰州市","regionEntitys":[{"code":"321201","region":"市辖区"},{"code":"321202","region":"海陵区"},{"code":"321203","region":"高港区"},{"code":"321204","region":"姜堰区"},{"code":"321281","region":"兴化市"},{"code":"321282","region":"靖江市"},{"code":"321283","region":"泰兴市"}]},{"code":"321300","region":"宿迁市","regionEntitys":[{"code":"321301","region":"市辖区"},{"code":"321302","region":"宿城区"},{"code":"321311","region":"宿豫区"},{"code":"321322","region":"沭阳县"},{"code":"321323","region":"泗阳县"},{"code":"321324","region":"泗洪县"}]}]};

  // 生成随机地址的方法
  function getRandomAddr() {
    var address = '';

    // 获取一级地址（省）
    var level1 = jsonData.region;

    // 获取二级地址（市）
    var level2 = '';
    if (jsonData.regionEntitys && jsonData.regionEntitys.length > 0) {
      var cityIndex = Math.floor(Math.random() * jsonData.regionEntitys.length);
      level2 = jsonData.regionEntitys[cityIndex].region;
    }

    // 获取三级地址（区）
    var level3 = '';
    if (jsonData.regionEntitys && jsonData.regionEntitys.length > 0) {
      var districtIndex = Math.floor(Math.random() * jsonData.regionEntitys.length);
      if (jsonData.regionEntitys[districtIndex].regionEntitys && jsonData.regionEntitys[districtIndex].regionEntitys.length > 0) {
        var districtList = jsonData.regionEntitys[districtIndex].regionEntitys;
        var districtItemIndex = Math.floor(Math.random() * districtList.length);
        level3 = districtList[districtItemIndex].region;
      }
    }

    // 生成随机的具体地址和门牌号（四级地址）
    var streets = ['中山路', '长江路', '人民路', '建设路', '解放路',"和平路","航金大道","兰陵路"];
    var randomStreet = streets[Math.floor(Math.random() * streets.length)];
    var doorNumber = Math.floor(Math.random() * 100) + 1;
    var level4 = level3 + randomStreet + doorNumber + '号';

    // 生成地址
    address = level1 + level2 + level3 + level4;
    return address;
}

</script>

<style>

.el-header {
  background-color: #333;
}

.el-calendar-table .el-calendar-day {
  height: 54px;
}

.el-button {
  border:none;
}

.el-card__header {
  padding: 8px 20px;
}

.text {
  font-size: 14px;
}

.item {
  margin-bottom: 18px;
}

.clearfix:before,
.clearfix:after {
  display: table;
  content: "";
}
.clearfix:after {
  clear: both
}


</style>
